package com.lagou.service.impl;

import com.lagou.controller.service.CodeServiceFeignClient;
import com.lagou.dao.TokenDao;
import com.lagou.dao.UserDao;
import com.lagou.pojo.Token;
import com.lagou.pojo.User;
import com.lagou.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenDao tokenDao;

    @Autowired
    private CodeServiceFeignClient codeServiceFeignClient;

    /**
     * 注册用户
     * @param email
     * @param password
     * @param code
     * @return
     */
    @Override
    public boolean registerUser(String email, String password, String code) {
        if(codeServiceFeignClient.validateCode(email,code) != 0){
            log.error("code is error,email:{},code:{}",email,code);
            return false;
        }

        if(isRegister(email)){
            log.error("email is error,email:{}",email);
            return false;
        }

        User user = User.builder()
                .email(email)
                .password(password)
                .build();

        userDao.save(user);

        return true;
    }

    /**
     * 判断邮箱是否注册
     * @param email
     * @return
     */
    @Override
    public boolean isRegister(String email) {
        return userDao.countByEmail(email) > 0;
    }

    @Override
    public String getEmailByToken(String token) {
        return tokenDao.getByToken(token).getEmail();
    }

    @Override
    public Token loginUser(String email, String password) {
        User user = userDao.getByEmailAndPassword(email, password);
        if(user == null){
            log.debug("login fail,email:{},password:{}",email,password);
            return null;
        }

        String uuid = UUID.randomUUID().toString();
        Token token = Token.builder()
                .email(email)
                .token(uuid)
                .build();

        tokenDao.save(token);

        return token;
    }


}
